package com.example.chapter5.controller;

import com.example.chapter5.entity.Blog;
import com.example.chapter5.mapper.BlogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
public class BlogController {
    @Autowired
    private BlogMapper blogService;
    //显示所有博客内容
//    @GetMapping("/api/blogs")
//    public List<Blog> getBlog() {
//        //通过service查询博客
//        return blogService.findAll();
//    }
    //进行分页显示，使用limit和offset
    //调用接口的时候，需要传递页面的参数，并且设置默认值
    //例如 http://localhost:8080/api/blogs?page=1&size=10
    @GetMapping("/api/blogs")
    public ResponseEntity getBlogsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10")int size) {
        //获取分页的数据
        List<Blog> blogs= blogService.findBlogsByPage(page, size);
        //获取博客总数量
        int count = blogService.countBlogs();
        //使用map打包博客数据和博客数量
        Map<String,Object> map = new HashMap<>();
        map.put("blogs", blogs);
        map.put("count", count);
        return ResponseEntity.ok(map);
    }
}

